import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import {
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Drawer,
  Divider,
  IconButton,
  Typography,
  Box,
  Collapse,
  useMediaQuery,
  useTheme,
  CircularProgress,
  ListItemButton,
} from '@mui/material';
import {
  ChevronLeft as ChevronLeftIcon,
  Home as HomeIcon,
  Category as CategoryIcon,
  LocalOffer as TagIcon,
  Add as AddIcon,
  ExpandLess,
  ExpandMore,
  Folder as FolderIcon,
  FolderOpen as FolderOpenIcon,
  Description as DescriptionIcon,
  Article as ArticleIcon,
  CreateNewFolder as CreateNewFolderIcon,
  NoteAdd as NoteAddIcon,
} from '@mui/icons-material';
import axios from 'axios';

// 修改为响应式的drawerWidth
const Sidebar = ({ open, handleDrawerClose }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  
  // 根据设备类型设置不同的宽度
  const drawerWidth = isMobile ? 320 : 480;
  
  const [categories, setCategories] = useState([]);
  const [expandedCategories, setExpandedCategories] = useState({});
  const [categoryKnowledges, setCategoryKnowledges] = useState({});
  const [loadingKnowledges, setLoadingKnowledges] = useState({});

  useEffect(() => {
    // 获取分类列表
    const fetchCategories = async () => {
      try {
        const response = await axios.get('/api/category');
        setCategories(response.data);
      } catch (error) {
        console.error('获取分类失败:', error);
      }
    };

    fetchCategories();
  }, []);

  const handleCategoryClick = (categoryId) => {
    setExpandedCategories(prev => ({
      ...prev,
      [categoryId]: !prev[categoryId]
    }));
    
    // 如果展开分类，并且该分类下还没有加载知识条目，则加载知识条目
    if (!expandedCategories[categoryId] && !categoryKnowledges[categoryId]) {
      fetchCategoryKnowledges(categoryId);
    }
  };
  
  // 获取分类下的知识条目
  const fetchCategoryKnowledges = async (categoryId) => {
    setLoadingKnowledges(prev => ({ ...prev, [categoryId]: true }));
    try {
      const response = await axios.get(`/api/knowledge?category_id=${categoryId}&page=1&page_size=10`);
      setCategoryKnowledges(prev => ({
        ...prev,
        [categoryId]: response.data.data
      }));
    } catch (error) {
      console.error(`获取分类 ${categoryId} 的知识条目失败:`, error);
    } finally {
      setLoadingKnowledges(prev => ({ ...prev, [categoryId]: false }));
    }
  };

  const handleNavigate = (path) => {
    navigate(path);
    if (isMobile) {
      handleDrawerClose();
    }
  };

  const renderCategoryTree = (category, level = 0) => {
    const isExpanded = expandedCategories[category.id];
    const hasChildren = category.children && category.children.length > 0;
    const hasKnowledges = categoryKnowledges[category.id] && categoryKnowledges[category.id].length > 0;
    const isLoading = loadingKnowledges[category.id];
    
    // 计算缩进，每一级增加2个单位的缩进
    const indentLevel = level * 2;

    return (
      <React.Fragment key={category.id}>
        <ListItem 
          disablePadding
          sx={{ display: 'block' }}
        >
          <ListItemButton
            onClick={() => handleNavigate(`/category/${category.id}`)}
            sx={{ pl: 2 + indentLevel }}
          >
            {(hasChildren || hasKnowledges || isLoading) && (
              <IconButton 
                size="small" 
                onClick={(e) => {
                  e.stopPropagation();
                  handleCategoryClick(category.id);
                }}
              >
                {isExpanded ? <ExpandLess /> : <ExpandMore />}
              </IconButton>
            )}
            <ListItemIcon>
              {isExpanded ? <FolderOpenIcon /> : <FolderIcon />}
            </ListItemIcon>
            <ListItemText primary={category.name} />
            <Box sx={{ display: 'flex', ml: 1 }}>
              <IconButton 
                size="small" 
                onClick={(e) => {
                  e.stopPropagation();
                  handleNavigate(`/category/new?parent_id=${category.id}`);
                }}
                title="创建子分类"
              >
                <CreateNewFolderIcon fontSize="small" />
              </IconButton>
              <IconButton 
                size="small" 
                onClick={(e) => {
                  e.stopPropagation();
                  handleNavigate(`/knowledge/new?category_id=${category.id}`);
                }}
                title="创建知识"
              >
                <NoteAddIcon fontSize="small" />
              </IconButton>
            </Box>
          </ListItemButton>
        </ListItem>
        <Collapse in={isExpanded} timeout="auto" unmountOnExit>
          <List component="div" disablePadding>
            {/* 显示子分类，递归调用并增加层级 */}
            {hasChildren && category.children.map(child => renderCategoryTree(child, level + 1))}
            
            {/* 显示该分类下的知识条目 */}
            {isLoading ? (
              <Box sx={{ display: 'flex', justifyContent: 'center', py: 1 }}>
                <CircularProgress size={20} />
              </Box>
            ) : (
              hasKnowledges && categoryKnowledges[category.id].map(knowledge => (
                <ListItem 
                  key={knowledge.id}
                  disablePadding
                >
                  <ListItemButton 
                    onClick={() => handleNavigate(`/knowledge/${knowledge.id}`)}
                    sx={{ pl: 4 + indentLevel }}
                  >
                    <ListItemIcon>
                      <ArticleIcon fontSize="small" />
                    </ListItemIcon>
                    <ListItemText 
                      primary={knowledge.title} 
                      primaryTypographyProps={{ 
                        variant: 'body2',
                        noWrap: true,
                        title: knowledge.title
                      }}
                    />
                  </ListItemButton>
                </ListItem>
              ))
            )}
          </List>
        </Collapse>
      </React.Fragment>
    );
  };

  return (
    <Drawer
      sx={{
        width: drawerWidth,
        flexShrink: 0,
        '& .MuiDrawer-paper': {
          width: drawerWidth,
          boxSizing: 'border-box',
        },
      }}
      variant={isMobile ? "temporary" : "persistent"}
      anchor="left"
      open={open}
      className="sidebar-drawer"
    >
      <Box sx={{ display: 'flex', alignItems: 'center', padding: 2, justifyContent: 'space-between' }}>
        <Typography variant="h6" noWrap component="div">
          知识管理系统
        </Typography>
        <IconButton onClick={handleDrawerClose}>
          <ChevronLeftIcon />
        </IconButton>
      </Box>
      <Divider />
      <List>
        <ListItem disablePadding>
          <ListItemButton onClick={() => handleNavigate('/')}>
            <ListItemIcon>
              <HomeIcon />
            </ListItemIcon>
            <ListItemText primary="首页" />
          </ListItemButton>
        </ListItem>
        <ListItem disablePadding>
          <ListItemButton onClick={() => handleNavigate('/categories')}>
            <ListItemIcon>
              <CategoryIcon />
            </ListItemIcon>
            <ListItemText primary="分类管理" />
          </ListItemButton>
        </ListItem>
        <ListItem disablePadding>
          <ListItemButton onClick={() => handleNavigate('/tags')}>
            <ListItemIcon>
              <TagIcon />
            </ListItemIcon>
            <ListItemText primary="标签管理" />
          </ListItemButton>
        </ListItem>
        <ListItem disablePadding>
          <ListItemButton onClick={() => handleNavigate('/knowledge/new')}>
            <ListItemIcon>
              <AddIcon />
            </ListItemIcon>
            <ListItemText primary="新建知识" />
          </ListItemButton>
        </ListItem>
      </List>
      <Divider />
      <Box sx={{ padding: 2 }}>
        <Typography variant="subtitle2" color="text.secondary">
          知识分类
        </Typography>
      </Box>
      <List>
        {categories.map(category => renderCategoryTree(category))}
      </List>
    </Drawer>
  );
};

export default Sidebar;